package com.itheima.pinda.biz;

import cn.hutool.core.util.StrUtil;
import com.itheima.pinda.file.domain.FileDO;
import com.itheima.pinda.file.enumeration.DataType;
import com.itheima.pinda.utils.NumberHelper;
import com.itheima.pinda.utils.ZipUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class FileBiz {

    /**
     * 构建新的文件名
     *
     * @param filename
     * @param order
     * @return
     */
    private static String buildNewFileName(String filename, Integer order) {
        return StrUtil.strBuilder(filename).insert(filename.indexOf("."), "(" + order + ")").toString();
    }

    /**
     * 下载文件
     *
     * @param list
     * @param request
     * @param response
     */
    public void down(List<FileDO> list, HttpServletRequest request, HttpServletResponse response) throws Exception {
        int fileSize = list.stream()
                .filter((fileDO) -> fileDO != null && !DataType.DIR.eq(fileDO.getDataType()) && StringUtils.isNotEmpty(fileDO.getUrl()))
                .mapToInt(file -> NumberHelper.intValueOf0(file.getSize()))
                .sum();
        String extName = list.get(0).getSubmittedFileName();
        if (list.size() > 1) {
            extName = StringUtils.substring(extName, 0,
                    StringUtils.lastIndexOf(extName, ".")) +
                    "等.zip";
        }
        Map<String, String> map = new LinkedHashMap<>(list.size());
        Map<String, Integer> duplicateFile = new HashMap<>(list.size());

        list.stream()
                .filter((fileDO) -> fileDO != null && !DataType.DIR.eq(fileDO.getDataType()) && StringUtils.isNotEmpty(fileDO.getUrl()))
                .forEach(file -> {
                    String fileName = file.getSubmittedFileName();
                    if (map.containsKey(fileName)) {
                        if (duplicateFile.containsKey(fileName)) {
                            duplicateFile.put(fileName, duplicateFile.get(fileName) + 1);
                        } else {
                            duplicateFile.put(fileName, 1);
                        }
                        fileName = buildNewFileName(fileName, duplicateFile.get(fileName));
                    }
                    map.put(fileName, file.getUrl());
                });

        ZipUtils.zipFilesByInputStream(map, Long.valueOf(fileSize), extName, request, response);
    }
}
